#include <brpc/server.h>
#include <butil/logging.h>

#include <iostream>
#include <string>

#include "main.pb.h"

// 0. 完成Protobuf的Echo方法
class EchoServiceImpl : public example::EchoService {
   public:
    void Echo(::google::protobuf::RpcController* controller,
              const ::example::EchoRequest* request,
              ::example::EchoResponse* response,
              ::google::protobuf::Closure* done) {
        brpc::ClosureGuard closure_guard(done);

        std::string req_str = request->message();
        std::cout << "收到请求: " << req_str << std::endl;

        response->set_message(req_str);
    }
};

int main() {
    // 关闭 brpc 的日志输出
    logging::LoggingSettings log_set;
    log_set.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(log_set);

    // 1. 搭建服务器
    brpc::Server server;

    // 2. 向服务器中，新增EchoService服务
    EchoServiceImpl echo_service;
    int ret = server.AddService(
        &echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);

    // 3. 启动服务器
    brpc::ServerOptions options;
    options.idle_timeout_sec =
        -1;                   // 连接空闲超时时间，超时后连接关闭。-1为不会超时
    options.num_threads = 2;  // id线程数量

    ret = server.Start(8080, &options);

    if (-1 == ret) {
        std::cout << "服务启动失败" << std::endl;
        return -1;
    }

    // 4. 等待
    server.RunUntilAskedToQuit();

    return 0;
}